package com.pansoft.openplanet.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.efounder.utils.NumberTextWatcher;
import com.efounder.utils.ResStringUtil;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.bean.Account;
import com.pansoft.openplanet.bean.AssetListBean;
import com.pansoft.openplanet.bean.WalletBean;
import com.pansoft.openplanet.constant.IPAssetsConstant;
import com.pansoft.openplanet.db.AccountDao;
import com.pansoft.openplanet.util.BalanceUtil;
import com.pansoft.openplanet.util.BtcTransactionManager;
import com.pansoft.openplanet.util.ChainParamsUtil;
import com.pansoft.openplanet.util.DecimalDigitsInputFilter;
import com.pansoft.openplanet.util.EosNetParamUtil;
import com.pansoft.openplanet.util.TCRequestUtil;
import com.pansoft.openplanet.util.UTXOTransactionManager;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author : zzj
 * @e-mail : zhangzhijun@pansoft.com
 * @date : 2019/4/3 10:51
 * @desc :  转账界面
 * @version: 1.0
 */
public class WalletTransferActivity extends TCBaseActivity implements View.OnClickListener {

    public static final String TAG = "WalletTransferActivity";
    private TextView tv_wallet_name;
    //付款地址
    private TextView tvPay;
    //备注
    EditText et_add_remark;
    //金额
    EditText etAmount;
    //收款地址
    EditText etReceive;
    //代币单位
    TextView tv_token_name;

    LinearLayout llExpense;
    TextView tvExpense;

    TextView tvTitle;
    private SeekBar seekBar;
    private TextView tvMinGas;
    private TextView tvMaxGas;
    private LinearLayout llSeekbar;
    private LinearLayout llAccountContainer;//eos账户选择

    public static final int COMMEN_TRANSFER = 1;//普通转账
    public static final int TOKEN_TRANSFER = 2; //代币转账
    public static final int QRCODE_TRANSFER = 3; //扫码普通转账
    public static final int QRCODE_TOKEN_TRANSFER = 4; //扫码代币转账

    //转账模式
    private int transferMode = COMMEN_TRANSFER;
    //钱包货币余额
    private String balance = "0";
    //代币余额
    private String assetBalance = "0";
    //代币单位
    private String assetUnit;
    private AssetListBean assetListBean;
    //当前钱包名
    private String curWalletName;
    //当前地址
    private String curAddress;
    //默认手续费
    private String gas = "0.0004";
    //默认链
    private int ipaChainId = IPAssetsConstant.CHAIN_ID_ETH;

    private List<WalletBean> walletBeans = new ArrayList<>();
    private BtcTransactionManager btcTransactionManager;

    private AccountDao accountDao;
    private Account curAccount;
    private String[] items;



    /**
     * @param walletName    账户名
     * @param mode          mode ETH， BTC等
     * @param address       账户地址
     * @param balance       账户余额
     * @param assetListBean assetListBean 为null 表示普通转账
     * @param accountType 钱包类型，0是子钱包，1是观察钱包，2是冷钱包
     */
    public static void start(Context context, String walletName, int mode, String address,
                             String balance, AssetListBean assetListBean, int accountType) {
        Intent starter = new Intent(context, WalletTransferActivity.class);
        starter.putExtra("walletName", walletName);
        starter.putExtra("mode", mode);
        starter.putExtra("address", address);
        starter.putExtra("balance", balance);
        starter.putExtra("assetBean", assetListBean);
        starter.putExtra("accountType", accountType);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.assets_activity_wallet_transfer);
        ipaChainId = getIntent().getIntExtra("mode", IPAssetsConstant.CHAIN_ID_ETH);
        accountDao = new AccountDao(this);
        initView();
        initIntentData();
    }

    private void initView(){
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tv_token_name = (TextView) findViewById(R.id.tv_token_name);
        tv_wallet_name = (TextView) findViewById(R.id.tv_wallet_name);
        et_add_remark = (EditText) findViewById(R.id.et_add_remark);
        tvPay = (TextView) findViewById(R.id.tv_pay);
        etReceive = (EditText) findViewById(R.id.et_receive);
        etAmount = (EditText) findViewById(R.id.et_amount);
        etAmount.addTextChangedListener(new NumberTextWatcher(etAmount));
        tvExpense = (TextView) findViewById(R.id.tv_expense);
        tvExpense.setOnClickListener(this);
    }


    /**
     * 初始化传递过来的数据
     */
    private void initIntentData() {
        balance = getIntent().getStringExtra("balance") == null ? "0" : getIntent().getStringExtra("balance");
        if (balance != null) {
            balance = balance.replace("BTC", "");
        }
        curWalletName = getIntent().getStringExtra("walletName");
        curAddress = getIntent().getStringExtra("address");
        if (curAddress== null) {
            curAddress = "";
        }
        curAccount = accountDao.getAccount(curAddress);
        //有这个表示代币转账
        assetListBean = (AssetListBean) getIntent().getSerializableExtra("assetBean");

        //这个表示扫码转账
        String tokenTrade = getIntent().getStringExtra("tokenTrade");

        if (ipaChainId == EosNetParamUtil.getEosChainId()) {
            etAmount.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(4)});
        } else {
            etAmount.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(8)});
        }
        //初始化默认标题
        tvTitle.setText(R.string.open_planet_transfer);

        if (assetListBean != null) {
            transferMode = TOKEN_TRANSFER;
            parseTokenData();
        } else if (tokenTrade != null) {
            parseQrCodeData(tokenTrade);
        } else {
            transferMode = COMMEN_TRANSFER;
            parseCommonData();
        }
    }

    /**
     * 解析普通转账数据（eth转账）
     */
    private void parseCommonData() {
//        if (ipaChainId == IPAssetsConstant.CHAIN_ID_ETH) {
//            assetUnit = "ETH";
//        } else if (ipaChainId == IPAssetsConstant.CHAIN_ID_BTC) {
//            assetUnit = "BTC";
//            tvExpense.setText(gas + " feePerKb");
//        } else if (ipaChainId == EosNetParamUtil.getEosChainId()) {
//            assetUnit = "EOS";
//            tvExpense.setText(gas + " eos");
//        }
        assetUnit = ChainParamsUtil.getAssetUnitByChainId(ipaChainId,tvExpense,gas);
//        tvBalance.setText(getString(R.string.open_planet_balance_with_unit, balance, assetUnit));
        setViewData();
    }

    /**
     * 解析代币转账数据
     */
    private void parseTokenData() {

        assetUnit = assetListBean.getName();
        assetBalance = assetListBean.getBalance();
        try {
            assetBalance = BalanceUtil.formatPrice(Double.valueOf(assetBalance), true, 8);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            assetBalance = assetListBean.getBalance();
        }
//        tvBalance.setText(getString(R.string.open_planet_balance_with_unit, assetBalance, assetUnit));
        setViewData();
    }

    /**
     * 解析扫描转账数据
     */
    private void parseQrCodeData(String tokenTrade) {
        try {
            JSONObject jsonObject = new JSONObject(tokenTrade);
            //收款人
            String receiveAddress = jsonObject.getString("walletAddress");
            etReceive.setText(receiveAddress);
            //是否是 代币转账
            boolean isTokenAcount = jsonObject.getBoolean("isTokenAccount");
            //转账金额
            etAmount.setText(jsonObject.getString("amount"));
            //合约地址
            String contractAddress = jsonObject.getString("contractAddress");

            String chainId = jsonObject.optString("chainId", "2");
            // 钱包单位名称
            assetUnit = jsonObject.optString("tokenUnit", "");
            try {
                ipaChainId = Integer.valueOf(chainId);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }

            initView();
            //默认使用currentshow 钱包转账
            curAccount = new AccountDao(this).getCurrentShowAccount(ipaChainId);

            if (curAccount != null) {
                curWalletName = curAccount.getAcccountName();
                curAddress = curAccount.getAddress();
                if (isTokenAcount) {
//                    String chainId = jsonObject.getString("chainId");
                    String tokenId = jsonObject.getString("tokenId");
                    initTokenData(curAddress, chainId, tokenId);
                } else {
                    //二维码非代币转账(分为 eth非代币 btc 或者eos)
                    if (ipaChainId == IPAssetsConstant.CHAIN_ID_ETH) {
                        initTokenData(curAddress, chainId, "");
                    } else if (ipaChainId == IPAssetsConstant.CHAIN_ID_BTC) {
                        parseCommonData();
//                        syncBtcAccount(account.getAddress(), account.getFileName());
                        UTXOTransactionManager.getBalance( TAG, curAccount);
                    } else if (ipaChainId == EosNetParamUtil.getEosChainId()) {
                        setViewData();
                    }

                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    /**
     * 初始化代币数据
     *
     * @param curAddress
     * @param chainId
     */
    private void initTokenData(final String curAddress, final String chainId, final String tokenId) {
        final HashMap<String, String> map = new HashMap<>();

        boolean isShowTokenBalance = true;
        map.put("chainID", chainId);

        if (!"".equals(tokenId)) {
            map.put("tokenID", tokenId);
            isShowTokenBalance = false;
        } else {
            //todo 故意写一个错误的字段名
            map.put("tokenId", "3");
        }

        map.put("userAddress", curAddress);

        final boolean finalIsShowTokenBalance = isShowTokenBalance;
        TCRequestUtil.getCommonRequest(TAG, "chain/getTokenInfo", map,
                new TCRequestUtil.TCRequestCallback() {
                    @Override
                    public void onSuccess(String response) {
                        dismissLoading();

                        Log.i(TAG, response + "");
                        net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(response);
                        //{"result":"success","AddressBalance":"0","TokenInfo":{"balance":"0","blockChainID":"2",
                        // "tokenAddress":"0xcb97e65f07da24d46bcdd078ebebd7c6e6e3d750","tokenDecimals":8,"tokenFullName":"Bytom",
                        // "tokenID":"10","tokenIcon":"http://cdn.openserver.cn/images/eth/tokens/btm.png","tokenName":"BTM"}}
                        if (jsonObject.getString("result").equals("success")) {
                            if (!tokenId.equals("") && !tokenId.equals("")) {
                                if (jsonObject.containsKey("TokenInfo")) {
                                    net.sf.json.JSONObject tokenInfoObject = jsonObject.getJSONObject("TokenInfo");
                                    assetUnit = tokenInfoObject.optString("tokenName");
                                    String assetBalance = tokenInfoObject.optString("balance", "0");
//                                    tvBalance.setText(getString(R.string.open_planet_balance_with_unit, assetBalance, assetUnit));

                                    assetListBean = new AssetListBean.Builder().address(tokenInfoObject.optString("tokenAddress"))
                                            .balance(assetBalance)
                                            .id(tokenInfoObject.optString("tokenID"))
                                            .blockChainID(tokenInfoObject.optString("blockChainID"))
                                            .name(tokenInfoObject.optString("tokenName"))
                                            .icon(tokenInfoObject.optString("tokenIcon"))
                                            .tokenDecimals(tokenInfoObject.optInt("tokenDecimals"))
                                            .build();
                                    setViewData();
                                }
                            } else {

                                balance = jsonObject.getString("AddressBalance");
                                if (!"0".equals(balance) && !"".equals(balance)) {
                                    balance = BalanceUtil.formatPrice(Double.valueOf(balance), true, 8);
                                }
//                                tvBalance.setText(getString(R.string.open_planet_balance_with_unit, balance, assetUnit));
//                                mode = IPAssetsConstant.CHAIN_ID_ETH;
                                parseCommonData();
                            }

                        } else {
                            parseCommonData();
                        }
                    }

                    @Override
                    public void onFail(String error) {
                        dismissLoading();
                        setViewData();

                    }
                });

    }

    //设置部分view 的数据
    private void setViewData() {
        tv_token_name.setText(assetUnit);
        tv_wallet_name.setText(curWalletName+"("+getString(R.string.open_planet_balance_with_unit, balance, "")+")");
//        tvBalance.setText(getString(R.string.open_planet_balance_with_unit, balance, assetUnit));
        tvPay.setText(curAddress);
        tvTitle.setText(assetUnit+" " + ResStringUtil.getString(R.string.open_planet_transfer));
    }

    @Override
    public void onClick(View v) {

    }
}
